// import { SlateElement } from "@wangeditor/editor";

import { uploadFile } from "@/api/bench";
import { PxMessage } from "px-ui";
type InsertFnType = (url: string, alt: string, href: string) => void;
// 自定义校验链接
function customCheckLinkFn(text: string, url: string): string | boolean | undefined {
  if (!url) {
    return;
  }
  if (url.indexOf("http") !== 0) {
    return "链接必须以 http/https 开头";
  }
  return true;
}
// 自定义转换链接 url
// function customParseLinkUrl(url: string): string {
//   if (url.indexOf("http") !== 0) {
//     return `http://${url}`;
//   }
//   return url;
// }
// 自定义校验图片
function customCheckImageFn(src: string): boolean | undefined | string {
  if (!src) {
    return;
  }
  if (src.indexOf("http") !== 0) {
    return "图片网址必须以 http/https 开头";
  }
  return true;
}

// 转换图片链接
function customParseImageSrc(src: string): string {
  if (src.indexOf("http") !== 0) {
    return `http://${src}`;
  }
  return src;
}
export const editorMenuConfig = {
  MENU_CONF: {
    // insertLink: {
    //   checkLink: customCheckLinkFn, // 也支持 async 函数
    //   parseLinkUrl: customParseLinkUrl // 也支持 async 函数
    // },
    // editLink: {
    //   checkLink: customCheckLinkFn, // 也支持 async 函数
    //   parseLinkUrl: customParseLinkUrl // 也支持 async 函数
    // },
    // insertImage: {
    //   checkImage: customCheckImageFn, // 也支持 async 函数
    //   parseImageSrc: customParseImageSrc // 也支持 async 函数
    // },
    // editImage: {
    //   checkImage: customCheckImageFn, // 也支持 async 函数
    //   parseImageSrc: customParseImageSrc // 也支持 async 函数
    // },
    uploadImage: {
      fieldName: "file",
      server: "/ifp/sharing/api/v1/file/upload",
      withCredentials: true,
      maxFileSize: 20 * 1024 * 1024, // 20M
      onBeforeUpload(file: File) {
        const acceptList = ["jpg", "png", "jpeg", "gif", "bmp"];
        let fileType = file.name.split(".").pop().toLowerCase();
        if (acceptList.indexOf(fileType) === -1) {
          PxMessage.error("只能上传 jpg/png/jpeg/gif/bmp 格式的图片");
          return false;
        } else if (file.size / 1024 / 1024 > 20) {
          PxMessage.error("上传图片大小不能超过20M");
          return false;
        }
        return file;
      },
      // 单个文件上传成功之后
      onSuccess() {
        PxMessage.success("图片上传成功");
      },

      // 单个文件上传失败
      onFailed() {
        PxMessage.error("图片上传失败，请重试");
      },
      async customUpload(file: File, insertFn: InsertFnType) {
        const formData = new FormData();
        formData.append("file", file);
        formData.append("moduleName", "");
        const res: any = await uploadFile(formData);
        if (res) {
          const { fileUrl, fileName } = res;
          // file 即选中的文件
          // 自己实现上传，并得到图片 url alt href
          // 最后插入图片
          loadImage({ url: fileUrl, callBack: () => insertFn(fileUrl, fileName, fileUrl) });
        }
      }
    },
    uploadVideo: {
      fieldName: "file",
      server: "/ifp/sharing/api/v1/file/upload",
      withCredentials: true,
      maxFileSize: 1024 * 1024 * 1024, // 1G
      // 单个文件上传成功之后
      onSuccess() {
        PxMessage.success("视频上传成功");
      },

      // 单个文件上传失败
      onFailed() {
        PxMessage.error("视频上传失败，请重试");
      },
      async customUpload(file: File, insertFn: InsertFnType) {
        const formData = new FormData();
        formData.append("file", file);
        formData.append("moduleName", "");
        const res: any = await uploadFile(formData);
        if (res) {
          const { fileUrl, fileName } = res;
          loadVideoWithRetry({ url: fileUrl, callBack: () => insertFn(fileUrl, fileName, fileUrl) });
        }
      }
    }
  }
};
const loadImage = ({ url, maxAttempts = 10, currentAttempt = 1, callBack }) => {
  const img = new Image();

  img.onload = function () {
    // 成功加载时设置图片地址
    callBack();
  };

  img.onerror = function () {
    if (currentAttempt < maxAttempts) {
      console.log(`第 ${currentAttempt} 次尝试失败，正在重试...`);
      // 200ms后重试（可选延迟）
      setTimeout(() => {
        loadImage({ url, maxAttempts, currentAttempt: currentAttempt + 1, callBack });
      }, 200);
    } else {
      console.error(`图片加载失败，已尝试 ${maxAttempts} 次`);
    }
  };
  img.src = url;
};
function loadVideoWithRetry({ url, maxRetries = 10, callBack }) {
  let attempts = 0;
  function attemptLoading() {
    const tempVideo = document.createElement("video");
    tempVideo.style.display = "none";

    const cleanup = () => {
      tempVideo.removeEventListener("loadeddata", onSuccess);
      tempVideo.removeEventListener("error", onError);
      document.body.removeChild(tempVideo);
    };

    const onSuccess = () => {
      cleanup();
      // 成功时创建正式视频元素
      callBack();
      // const finalVideo = createVideoElement();
      // finalVideo.src = url;
      // document.getElementById("videoContainer").appendChild(finalVideo);
    };

    const onError = () => {
      cleanup();
      attempts++;

      if (attempts < maxRetries) {
        console.log(`请求失败，开始第 ${attempts + 1} 次重试...`);
        setTimeout(() => {
          attemptLoading();
        }, 200);
      } else {
        console.error(`视频加载失败，已重试 ${maxRetries} 次`);
      }
    };

    // 添加临时检测视频元素
    document.body.appendChild(tempVideo);
    tempVideo.addEventListener("loadeddata", onSuccess);
    tempVideo.addEventListener("error", onError);
    tempVideo.src = url;
  }

  // 开始首次尝试
  attemptLoading();
}
